# 16. 自定义指令
# 16.1 语法
一、定义语法:
局部指令:
new Vue({ directives:{ 指令名:配置对象 } }) new Vue({ directives:{ 指令名:回调函数 } })1
2
3
4
5
6
7
8
9
10
11全局指令:
Vue.directive(指令名, 配置对象) 或 Vue.directive(指令名, 回调函数) Vue.directive('fbind', { // 指令与元素成功绑定时(一上来) bind(element, binding) { // element就是DOM元素,binding就是要绑定的 element.value = binding.value }, // 指令所在元素被插入页面时 inserted(element, binding) { element.focus() }, // 指令所在的模板被重新解析时 update(element, binding) { element.value = binding.value } })1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
二、配置对象中常用的3个回调:
bind(element. binding):指令与元素成功绑定时调用inserted(element. binding):指令所在元素被插入页面时调用update(element. binding):指令所在模板结构被重新解析时调用
这里的
element是DOM元素,binding就是要绑定的对象,它包括以下属性:name,value,
oldValue,expression,arg,modifiers
三、备注:
- 指令定义时不加v-,但使用时要加
v-; - 指令名如果是多个单词,要使用
kebab-case命名方式,不要用camelCase命名。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>自定义指令</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<h2>{{name}}</h2>
<h2>当前的n值是:<span v-text="n"></span> </h2>
<!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> -->
<h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
<button @click="n++">点我n+1</button>
<hr/>
<input type="text" v-fbind:value="n">
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
new Vue({
el:'#root',
data:{
name:'尚硅谷',
n:1
},
directives:{
//big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。
/* 'big-number'(element,binding){
// console.log('big')
element.innerText = binding.value * 10
}, */
big(element,binding){
console.log('big',this) //注意此处的this是window
// console.log('big')
element.innerText = binding.value * 10
},
fbind:{
//指令与元素成功绑定时(一上来)
bind(element,binding){
element.value = binding.value
},
//指令所在元素被插入页面时
inserted(element,binding){
element.focus()
},
//指令所在的模板被重新解析时
update(element,binding){
element.value = binding.value
}
}
}
})
</script>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 16.2 回顾一个 DOM 操作
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.demo{
background-color: orange;
}
</style>
</head>
<body>
<button id="btn">点我创建一个输入框</button>
<script type="text/javascript" >
const btn = document.getElementById('btn')
btn.onclick = ()=>{
const input = document.createElement('input')
input.className = 'demo'
input.value = 99
input.onclick = ()=>{alert(1)}
document.body.appendChild(input)
input.focus()
// input.parentElement.style.backgroundColor = 'skyblue'
console.log(input.parentElement)
}
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33